import logging
import time
import sys
import os
from logging.handlers import RotatingFileHandler
from concurrent_log_handler import ConcurrentRotatingFileHandler

# 更健壮的路径处理方式
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)  # 直接添加当前目录到路径

# 创建日志目录
log_dir = os.path.join(current_dir, 'logs')
os.makedirs(log_dir, exist_ok=True)

# 配置基础日志格式
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 交易日志配置
trade_handler = ConcurrentRotatingFileHandler(
    os.path.join(log_dir, 'trade.log'),
    mode='a',
    maxBytes=10*1024*1024,
    backupCount=3,
    encoding='utf-8'
)
trade_handler.setFormatter(formatter)
trade_logger = logging.getLogger('trade')
trade_logger.setLevel(logging.DEBUG)
trade_logger.addHandler(trade_handler)

# 行情日志配置
market_handler = ConcurrentRotatingFileHandler(
    os.path.join(log_dir, 'market.log'),
    mode='a',
    maxBytes=10*1024*1024,
    backupCount=3,
    encoding='utf-8'
)
market_handler.setFormatter(formatter)
market_logger = logging.getLogger('market')
market_logger.setLevel(logging.DEBUG)
market_logger.addHandler(market_handler)

# 控制台日志配置
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)

# 根日志配置（仅处理未分类日志）
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.addHandler(console_handler)

logger = logging.getLogger('api')
logger.info("API日志系统初始化完成")

# 在main.py的日志配置中添加
logging.getLogger('trade').propagate = False
logging.getLogger('market').propagate = False

from utils.config import ConnectionConfig
from trade.api import TradeClient
from market.api import MarketClient
from trade.spi import TradeSpi
from market.spi import MarketSpi
from base.client import BaseClient

class MyTradeSpi(TradeSpi):
    """自定义交易回调处理"""
    def OnRtnOrder(self, order):
        logging.info(f"[交易回报] 订单状态更新: {order.order_id} - {order.status}")
        
    def OnRspUserLogin(self, response):
        if response.error_code:
            logging.error(f"交易登录失败: {response.error_msg}")
        else:
            logging.info("交易登录成功，开始发送订单...")
            # 示例下单
            self.api.send_order({
                "symbol": "600519",
                "price": 1800.0,
                "quantity": 100,
                "direction": "BUY",
                "order_type": "LIMIT"
            })

class MyMarketSpi(MarketSpi):
    """自定义行情回调处理"""
    def OnMarketData(self, data):
        logging.debug(f"[行情] {data.symbol} 最新价: {data.last_price} 成交量: {data.volume}")
        
    def OnRspSubMarketData(self, symbols):
        logging.info(f"已成功订阅: {', '.join(symbols)}")

def main():
    # 初始化配置
    config = ConnectionConfig(
        host="139.224.65.236",
        trade_port=9999,
        market_port=9998,
        trade_username="customer",
        trade_password="123456",
        market_username="customer",
        market_password="123456",
        auth_code="123456"
    )
    
    # 创建回调实例
    trade_spi = MyTradeSpi()
    market_spi = MyMarketSpi()
    
    try:
        # 初始化客户端
        trade_client = TradeClient(config, trade_spi)
        market_client = MarketClient(config, market_spi)
        
        # 增加双向引用绑定
        trade_spi.api = trade_client  # SPI持有API引用
        trade_client.spi = trade_spi  # API持有SPI引用
        
        # 增加双向引用绑定
        market_spi.api = market_client  # SPI持有API引用
        market_client.spi = market_spi  # API持有SPI引用

        # 建立连接
        logging.info("正在连接交易服务器...")
        trade_client.connect()
        market_client.connect()
        
        # 订阅行情
        market_client.subscribe(["600519", "000001"])
        
        # 保持主线程运行
        while True:
            time.sleep(1)
            
    except ConnectionError as e:
        logging.error(f"连接失败: {str(e)}")
    except KeyboardInterrupt:
        logging.info("用户中断，正在关闭连接...")
    finally:
        trade_client.close()
        market_client.close()
        logging.info("程序已安全退出")

if __name__ == "__main__":
    main() 